"use client";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useDrag } from "@use-gesture/react";
import { animated, useSpring } from "@react-spring/web";
import { setTimeout } from "timers";
interface IProps {
    onSwipe?: (dir: "left" | "right") => void;
    children: React.ReactNode[];
    threshold?: number;
    velocity?: number;
    scale?: number;
    data: any[];
    render?: (index: number) => React.ReactNode;
}

export const Swipeable: React.FC<IProps> = ({
    children,
    onSwipe,
    threshold = 100,
    velocity = 0.3,
    scale = 2,
    render,
    data = [0, 1, 2, 3, 4, 5],
}) => {
    const [style1, api1] = useSpring(() => {
        return {
            x: -100,
        };
    }, []);

    const animatedRef = useRef(false);
    const activeRef = useRef(0);
    const [active, setActive] = useState(0);
    //[0] [1] [2] [3] [9]
    //[0] [1] [2] [9]
    //[0] [1] [9]
    const updateActive = (n: number, dir: string) => {
        if (n < 0 || n > data.length - 1) return;
        setActive(n);
        if (n == 1) {
        } else if (n == data.length - 1) {
            if (dir == "left") {
                console.log(
                    api1.start({
                        x: -200,
                    })
                );
            }
        }

        return;
        if (!animatedRef.current) {
            animatedRef.current = true;
            activeRef.current = n;
            Promise.all(
                api1.start({
                    x: activeRef.current * 100,
                })
            ).then(() => {
                api1.set({
                    x: 0,
                });
                setActive(activeRef.current);
                animatedRef.current = false;
            });
        }
    };
    const MAX = 3;

    const showList = (() => {
        // const active = activeRef.current;
        console.log("active", active);
        const result = [data[active]];
        const prev = active - 1;
        const next = active + 1;
        if (prev < 0) {
            result.unshift("[placeholder start]");
        } else {
            result.unshift(data[prev]);
        }

        if (next > data.length - 1) {
            result.push("[placeholder end]");
        } else {
            result.push(data[next]);
        }
        console.log(result);
        return result.map((e) => (
            <div
                key={new Date().getTime() + e}
                className="w-[100px] h-full flex-shrink-0 bg-slate-600 text-white "
            >
                {e}
            </div>
        ));
    })();
    // api.start({ x: mx * scale });
    const invokeSwipe = (dir: Parameters<Required<IProps>["onSwipe"][0]>) => {
        console.log("dir", dir);
        console.log(api1);
        if (dir === "left") {
            // updateActive(active + 1, dir);
            // api1.pause("x");
            // Promise.all(
            //     api1.start({
            //         x: -200,
            //     })
            // ).then(() => {
            //     // api1.set({ x: -100 });
            //     api1.resume("x");
            //     // api1.set({ x: -100 });
            //     // setTimeout(() => {
            //     //     activeRef.current = activeRef.current + 1;
            //     //     setActive(activeRef.current);
            //     // });
            //     // setActive(active + 1);
            // });
            // activeRef.current -= 1;
            setActive(active - 1);
        }
        if (dir === "right") {
            // activeRef.current += 1;
            setActive(active + 1);
            // Promise.all(
            //     api1.start({
            //         x: 0,
            //     })
            // ).then(() => {
            //     api1.update({ x: -100 });
            //     setTimeout(() => {
            //         activeRef.current = activeRef.current - 1;
            //         setActive(activeRef.current);
            //     }, 1000);
            // });
        }
    };
    const bind = useDrag(
        (e) => {
            const {
                direction: [dx],
                movement: [mx],
                velocity: [vx],
                currentTarget,
                cancel,
                canceled,
                active,
            } = e;
            if (!active || canceled) {
                return;
            }

            const td = Math.min(
                (currentTarget as HTMLElement).clientWidth / 3,
                threshold
            );

            if (Math.abs(mx) < td || Math.abs(vx) < velocity) {
                return;
            }
            console.log(dx, mx);
            invokeSwipe?.(dx > 0 ? "right" : "left");
            cancel();
        },
        {
            axis: "x",
            preventScroll: true,
            trackTouch: true,
            filterTaps: true,
            pointer: {
                touch: true,
            },
        }
    );
    {
        /* <div className="h-[100px]">event: {JSON.stringify(event)}</div> */
    }
    {
        /* <animated.div style={style}>
                {React.cloneElement(children, {
                    ...bind(),
                    style: {
                        ...children.props.style,
                        touchAction: "pan-y",
                    },
                })}
            </animated.div> */
    }

    return (
        <>
            <div>{activeRef.current}</div>
            <div
                className="w-[100px] h-[300px] outline-2 outline-red-500 outline-double m-auto"
                {...bind()}
            >
                <animated.div
                    style={style1}
                    className="w-[300px]] h-full touch-pan-y flex flex-nowrap border-green-400 border-2 box-border"
                    // className="w-full h-full flex flex-nowrap touch-pan-y"
                >
                    {showList}
                </animated.div>
            </div>
        </>
    );

    return (
        <div className="w-full h-full flex flex-nowrap touch-pan-y" {...bind()}>
            <animated.div
                style={style1}
                className="flex-shrink-0 w-[50%] h-full"
            >
                <div className=" w-full h-5 bg-slate-600 text-white">
                    {active} : {JSON.stringify(style1.x)}
                </div>
            </animated.div>
            <animated.div
                style={style1}
                className="flex-shrink-0 w-[50%] h-full"
            >
                <div className="flex-shrink-0 w-full h-full bg-orange-400">
                    {JSON.stringify(style1.x)}
                </div>
            </animated.div>
        </div>
    );
};
